---
sidebar_position: 1
---
import { constants } from '@site/src/constants';
import CodeBlock from '@theme/CodeBlock';

# Upload & Download Files

run_code 和 run_jupyter 接口都支持文件相关的两个参数：

- files: 代码执行前要上传的文件，文件路径到文件base64内容的字典
- fetch_files: 代码执行结束后要取回的文件，文件路径的列表

因为参数的使用完全相同，下面以 run_code 接口为例说明文件的上传和下载。

## Upload

export const snippet1 = String.raw`import json
import base64
import requests

with open('flag.txt', 'rb') as f:
    content = f.read()
base64_content = base64.b64encode(content).decode('utf-8')

response = requests.post('${ constants.host }/run_code', json={
    'code': 'print(open("flag.txt").read())',
    'language': 'python',
    'files': {'flag.txt': base64_content}
})

print(json.dumps(response.json(), indent=2))
`

<CodeBlock language="python">
{snippet1}
</CodeBlock>

输出：

```json
{
  "status": "Success",
  "message": "",
  "compile_result": null,
  "run_result": {
    "status": "Finished",
    "execution_time": 0.018889427185058594,
    "return_code": 0,
    "stdout": "secret flag\n",
    "stderr": ""
  },
  "executor_pod_name": null,
  "files": {}
}
```

文件路径默认为相对脚本所在目录（每次随机生成的/tmp/tmpxxxx）的位置。 也可以指定 /tmp/flag.txt这种绝对路径。 如果指定的路径不存在，会先创建对应的文件夹。

## Download

export const snippet2 = String.raw`import json
import base64
import requests

response = requests.post('${ constants.host }/run_code', json={
    'code': 'open("flag.txt", "w").write("this is a secret")',
    'language': 'python',
    'fetch_files': ['flag.txt']
})

print(json.dumps(response.json(), indent=2))
print(base64.b64decode(response.json()['files']['flag.txt']).decode('utf-8'))
`

<CodeBlock language="python">
{snippet2}
</CodeBlock>

输出：

```json
{
  "status": "Success",
  "message": "",
  "compile_result": null,
  "run_result": {
    "status": "Finished",
    "execution_time": 0.023561477661132812,
    "return_code": 0,
    "stdout": "",
    "stderr": ""
  },
  "executor_pod_name": null,
  "files": {
    "flag.txt": "dGhpcyBpcyBhIHNlY3JldA=="
  }
}
this is a secret
```

文件路径的规则与上传部分相同。
